package api

import (
	"coroutine/api_client/handler/request"
	pb "coroutine/api_client/proto"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
)

func AddTicket(c *gin.Context) {
	var req request.AddTicketReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
			"data": err.Error(),
		})
		return
	}
	conn, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	client := pb.NewUserClient(conn)

	ticket, _ := client.AddTicket(c, &pb.AddTicketReq{
		TicketType:        req.TicketType,
		TicketStart:       req.TicketStart,
		TicketState:       req.TicketState,
		TicketTrainNumber: req.TicketTrainNumber,
		TicketSeatType:    req.TicketSeatType,
		TicketNumber:      int64(req.TicketNumber),
		TicketPrice:       float32(req.TicketPrice),
		TicketIdCard:      req.TicketIdCard,
	})
	c.JSON(200, ticket)
}

func UpdatedTicket(c *gin.Context) {
	var req request.UpdatedTicketReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
			"data": err.Error(),
		})
		return
	}
	conn, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	client := pb.NewUserClient(conn)

	ticket, _ := client.UpdatedTicket(c, &pb.UpdatedTicketReq{
		Id:           req.Id,
		TicketNumber: int64(req.TicketNumber),
	})
	c.JSON(200, ticket)
}
